//
//  Date+Extension.swift
//  MicroBlog
//
//  Created by Apple on 16/9/27.
//  Copyright © 2016年 Apple. All rights reserved.
//

import Foundation

extension Date {
   static func sinaDate(createAt: String) -> Date {
        //时间字符串不为空
        let dt = DateFormatter()
        dt.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        //指定本地化信息
        dt.locale = Locale(identifier: "en_US")
        //把字符串转化成时间对象
        let createAtDate = dt.date(from: createAt)!
        return createAtDate
    }
    
    var sinaDateString: String {
        let dt = DateFormatter()
        dt.locale = Locale(identifier: "en_US")
        if isThisYear(createAtDate: self) {
            //今年
            let currentCalendar = Calendar.current
            if currentCalendar.isDateInToday(self) {
                let timeInterVal = abs(self.timeIntervalSinceNow)
                if timeInterVal < 60 {
                    return "刚刚"
                } else if timeInterVal < 3600 {
                    let result = timeInterVal / 60
                    return "\(Int(result))分钟前"
                } else {
                    let result = timeInterVal / 3600
                    return "\(Int(result))小时前"
                }
            } else if currentCalendar.isDateInYesterday(self) {
                dt.dateFormat = "昨天: HH: mm"
            } else {
                //其他
                dt.dateFormat = "MM-dd: HH:mm"
            }
        } else {
            //不是今年
            dt.dateFormat = "yyyy-MM-dd HH:mm"
        }
        return dt.string(from: self)
    }
    
    //根据指定时间对象判断是否是今年
    private func isThisYear(createAtDate: Date) -> Bool {
        let dt = DateFormatter()
        dt.dateFormat = "yyyy"
        //指定本地化信息
        dt.locale = Locale(identifier: "en_US")
        //获取年份
        let createAtYear = dt.string(from: createAtDate)
        //获取当前时间的年份
        let currentDateYear = dt.string(from: Date())
        //判断时间年份是否相同
        return createAtYear == currentDateYear
    }
}
